
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片压缩并下载</title>
</head>
<body>
<input type="file" accept="image/*" id="fileInput">
<button id="compressBtn">压缩并下载</button>

<script>
document.getElementById('compressBtn').addEventListener('click', function() {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    
    if (file) {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        
        reader.onload = function(event) {
            const img = new Image();
            img.src = event.target.result;
            
            img.onload = function() {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                const maxWidth = 800;
                const scale = maxWidth / img.width;
                canvas.width = maxWidth;
                canvas.height = img.height * scale;
                
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                
                canvas.toBlob(function(blob) {
                    const compressedFile = new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() });
                    
                    const downloadLink = document.createElement('a');
                    downloadLink.href = URL.createObjectURL(compressedFile);
                    downloadLink.download = 'compressed_image.jpg';
                    downloadLink.click();
                }, 'image/jpeg', 0.7); // 0.7 是压缩质量，可根据需要调整
            };
        };
    } else {
        alert('请先选择图片文件');
    }
});
</script>
</body>
</html>
